package com.pl.myshop.business.service;

import com.google.common.collect.Lists;
import com.pl.myshop.provider.api.UesrService;
import com.pl.myshop.provider.domain.UmsAdmin;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: pl
 * @Date: 2020/3/22 20:26
 * @Description:
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference(version = "1.0.0")
    private UesrService uesrService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        UmsAdmin user = uesrService.getUserByUserName(userName);
        // 用户名匹配
        if (null!=user) {
            List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
            //授权
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(user.getRole());
            grantedAuthorities.add(grantedAuthority);
            return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
        }
        // 用户名不匹配
        else {
            return null;
        }
    }
}